$(document).ready(function(){
    /*左侧导航栏鼠标点击展开收起*/
    if($('.sidebar')[0]){
        var temp  = '<div class="showHideBar hideBar"><span></span></div>';
        $($('.sidebar')).append(temp);
        $('.sidebar').on('click','.showHideBar',function (){
           var orginW = 260;
           var minW = 20;
           var wLenOrigin = 270;
           var wLen = 270-(orginW - minW);
           var self = $(this);
           if(self.hasClass('hideBar')) {
               self.removeClass('hideBar').addClass('showBar');
               $('.sidebar').width(minW);
               $("#page-wrapper").css('marginLeft',wLen+'px');
           }
           else if(self.hasClass('showBar')) {
               self.removeClass('showBar').addClass('hideBar');
               $('.sidebar').width(orginW);
               $("#page-wrapper").css('marginLeft',wLenOrigin+'px');
           }
       });
    }

    //编辑页面上传图片的点击按钮
    var $edit = $(".input-file-edit");
    $edit.each(function(){
        var $w = $(this).siblings("img.obj-img").width();
        var $h = $(this).siblings("img.obj-img").height();
        $(this).width($w).height($h).find("input[type='file']").width($w).height($h);
    })

    //禁止input的 enter键提交表单
    $("input").keydown(function(event){
        if(event.keyCode==13){
            return false
        }
    })

});
//2017-6-1
var appUrl = $('#_ctx').val();
//上传图片
/**
 * 调用方法
 * data-action="goods"  商品图片
 * data-action="icon"  icon
 * data-action="image" 测试图片
 * data-action="base"  证件相关
 <input class="obj-input" name="banner" value="" type="hidden">
 <img class="obj-img" src="" style="display:none">
 <span class="input-file">
    <input data-image="banner" type="file"  data-action="goods" onchange="uploadImg(this)">
 </span>
 编辑页面 class替换为 input-file-edit
 默认单图 多图事件：uploadImg(this,true)
 appUrl 路径 <%=request.getContextPath()%>
 <input type="hidden" id="_ctx" value="<%=request.getContextPath()%>"/>
 **/
var flag = false;//flag是否多张
var uploadImg = function(obj,flag){
    //创建FormData对象
    var data = new FormData();
    var at = $(obj).attr("data-image");
    var action = $(obj).attr("data-action");
    //为FormData对象添加数据
    data.append('image', $(obj)[0].files[0]);

    //判定图片大小和尺寸
    if(getPhotoSize(obj,3)){
        var objUrl = getObjectURL(obj.files[0]);
        getImageWidth(objUrl, function(w, h) {
            var size = "?" + w + "/" + h;
            if (w > 750) {
                alert("图片尺寸太大，请处理成不大于750px");
                return false;
            }
            else{
                $.ajax({
                    url: appUrl + '/upload/' + action,
                    type: 'POST',
                    data: data,
                    cache: false,
                    contentType: false,
                    processData: false,
                    success: function (res) {
                        //获取图片尺寸
                        res = res + size;
                        //多图
                        if (flag) {
                            $(obj).before("<div class='detail-box'>" +
                                "<input type='hidden' name=" + at + " value=" + res + "  />" +
                                "<img class='test' src=" + res + " />" +
                                "<i class='fa fa-close'></i></div>");
                            //删除
                            $(".detail-box i").click(function () {
                                var detBox = $(this).parent();
                                $.ajax({
                                    url: appUrl + '/upload/remove',
                                    type: "POST",
                                    data: JSON.stringify({'name': res, 'id': 0}),
                                    dataType: "json",
                                    contentType: "application/json; charset=utf-8",
                                    success: function (res) {
                                        console.log(res);
                                        detBox.remove();
                                    }
                                });
                            });
                        }
                        //单图
                        else {
                            var _this = $(obj).parent();
                            _this.hide();
                            //预先取消绑定 -- 兼容webkit
                            _this.siblings(".obj-img").off("click");
                            _this.siblings(".obj-img").attr("src", res).show().on("click", function () {
                                $(obj).click();
                            });
                            _this.siblings(".obj-input").val(res).change();
                            _this.siblings("input.old-val").val(res).change();//编辑页面直接修改input的值
                        }
                    },
                    error: function () {
                        console.log("上传失败")
                    }
                });
            }
        });
    }
    //获取图片原始尺寸方法
    function getImageWidth(url,callback){
        var img = new Image();
        img.src = url;
        // 如果图片被缓存，则直接返回缓存数据
        if(img.complete){
            callback(img.width, img.height);
        }
        // 完全加载完毕的事件
        else{
            img.onload = function(){
                callback(img.width, img.height);
            }
        }
    }
    //判断图片大小
    function getPhotoSize(obj,imgSize){
        var photoExt = obj.value.substring(obj.value.lastIndexOf(".")+1).toLowerCase();//获得文件后缀名
        if(photoExt!='jpg'&&photoExt!='jpeg'&&photoExt!='bmp'&&photoExt!='png'&&photoExt!='gif'){
            alert("图片格式必须是.jpg/.jpeg/.bmp/.png!");
            return false;
        }
        var imgSize = imgSize || 3;
        var fileSize = 0;
        var isIE = /msie/i.test(navigator.userAgent) && !window.opera;
        if (isIE && !obj.files) {
            var filePath = obj.value;
            var fileSystem = new ActiveXObject("Scripting.FileSystemObject");
            var file = fileSystem.GetFile (filePath);
            fileSize = file.Size;
        }else {
            fileSize = obj.files[0].size;
        }
        fileSize=Math.round(fileSize/1024*100)/100; //单位为KB
        if(fileSize>imgSize*1024){
            alert("图片最大为"+imgSize+"M，请重新上传!");
            return false;
        }
        return fileSize;
    }
    //获取图片临时url -- 1.判断图片尺寸 2.可实现预览
    function getObjectURL(file) {
        var url = null ;
        if (window.createObjectURL!=undefined) { // basic
            url = window.createObjectURL(file) ;
        } else if (window.URL!=undefined) { // mozilla(firefox)
            url = window.URL.createObjectURL(file) ;
        } else if (window.webkitURL!=undefined) { // webkit or chrome
            url = window.webkitURL.createObjectURL(file) ;
        }
        return url ;
    }
};

/**
 * 调用 onclick="goamap()" 省市县class加 area
 * **/
//高德地图
var area = "";
function goamap(){
    area = "";
    $(".area select").each(function(){
        var _this = $(this);
        if($(this).find("option:selected").index() != "0") {
            area += _this.find("option:selected").text();
        }
    });
    //搜索关键词 过滤"市辖区"
    area = area.replace(/市辖区/,"");
    layer.open({
        type: 2,
        area: ['95%', '95%'],
        title: ['高德地图定位查询','text-align:center;background:#00A1D9;color:#fff'],
        content: [appUrl+'/admin/map?area='+encodeURI(area),'no'],
        success: function(layero, index){
            var body = layer.getChildFrame('body', index);
            body.find("#tipinput").val(area);
        }
    });
}

//正则
var regTel = /0?(13|14|15|17|18)[0-9]{9}/;//手机号
var regNumber = /^([+-]?)\d*\d+$/;//数字
var regInt = /^[1-9]\d*$/;//正整数
var regBob = /^([1-9]\d?|100)$/;//不能超过100的数字
var regPrice = /(^[1-9]\d*(\.\d{1,2})?$)|(^0(\.\d{1,2})?$)/;//价格 最多两位小数
var regCar = /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[A-Z]{1}[A-Z0-9]{4}[A-Z0-9挂学警港澳]{1}$/;//车牌号
var regId = /^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$|^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}([0-9]|X)$/;//身份证号
var regPhone = /^((0\d{2,3}-\d{7,8})|(1[34578]\d{9}))|([48]00\d+$)$/;//座机+手机+400电话
var regDrive = /^[a-zA-Z0-9]{17}$/;//行驶证号
var regCerty = /^[a-zA-Z0-9]{10,20}$/;//证件代码
//var regName = /^[\u4E00-\u9FA5a-zA-Z0-9_]{4,16}$/;//登录名
var regName = /^[a-zA-Z0-9_]{4,16}$/;//登录名
var regRreaName = /[\u4E00-\u9FA5]/;//真实姓名
var regEmail = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;//邮箱
var regJwd = /^[\-\+]?(0?\d{1,2}|0?\d{1,2}\.\d{1,}|1[0-7]?\d{1}|1[0-7]?\d{1}\.\d{1,}|180|180\.0{1,})(\,)[\-\+]?([0-8]?\d{1}|[0-8]?\d{1}\.\d{1,}|90|90\.0{1,})$/;//经纬度

//日期扩展 格式化方法
Date.prototype.Format = function (fmt) {
    var o = {
        "M+": this.getMonth() + 1, //月份
        "d+": this.getDate(), //日
        "h+": this.getHours()%12 == 0 ? 12 : this.getHours()%12, //小时
        "H+": this.getHours(), //小时
        "m+": this.getMinutes(), //分
        "s+": this.getSeconds(), //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
};

//console.log(new Date().Format("yyyy-MM-dd HH:mm:ss"))
//2017-8-16 16:12:35

//上传文件    判断文件不超过10MB的.docx文件
/**
 <input type="file" data-action="icon" data-image="avatar" onchange="uploadFile(this)">
 <input type="hidden" id="fileValue" value="">
 <input type="hidden" id="fileName" value="">
**/
var uploadFile = function(obj,type,size) {
    var filetypes = type;
    var filepath = obj.value;

    var targetSize = size || 10;
    var fileSize = 0;
    var isIE = /msie/i.test(navigator.userAgent) && !window.opera;
    if (isIE && !obj.files) {
        var filePath = obj.value;
        var fileSystem = new ActiveXObject("Scripting.FileSystemObject");
        var file = fileSystem.GetFile (filePath);
        fileSize = file.Size;
    }else {
        fileSize = obj.files[0].size;
    }
    fileSize=Math.round(fileSize/1024*100)/100; //单位为KB
    if(fileSize>targetSize*1024){
        alert("文件最大为"+targetSize+"M，请重新上传!");
        return false;
    }
    if (filepath) {
        var isnext = false;
        var fileend = filepath.substring(filepath.lastIndexOf("."));
        if (filetypes && filetypes.length > 0 && (filetypes == fileend)) {
        //创建FormData对象
            var data = new FormData();
            var action = $(obj).attr("data-action");
            //为FormData对象添加数据
            data.append('image', $(obj)[0].files[0]);
            $.ajax({
                url: appUrl + '/upload/' + action,
                type: 'POST',
                data: data,
                cache: false,
                contentType: false,
                processData: false,
                success: function (res) {
                    console.log(res);
        //            var fileName = $(obj).val().split("\\")
        //            fileName = fileName[fileName.length - 1];
                    $(obj).siblings("#fileValue").val(res).change();
                    $(obj).siblings("#fileName") && $(obj).siblings("#fileName").attr("src", res).show();
                    $(obj).siblings("#fileText") && $(obj).siblings("#fileText").val(res).show();
                },
                error: function () {
                    console.log("上传失败")
                }
            })
        }
        else{
            alert("不接受此文件类型！");
            obj.value = "";
            return false;
        }
    } else {
        return false;
    }
}
//2017-9-21 编辑/详情 => 分页码
var curNum = window.location.search;
if(curNum.indexOf("curNum") != "-1") {
    curNum = curNum.split("curNum")[1];
    curNum = parseInt(curNum.split("=")[1]) || 1;
}

/**vue upload**/
var vueUploadImg = function(obj,flag){
    //创建FormData对象
    var data = new FormData();
    var at = $(obj).attr("data-image");
    var action = $(obj).attr("data-action");
    //为FormData对象添加数据
    data.append('image', $(obj)[0].files[0]);

    //判定图片大小和尺寸
    if(getPhotoSize(obj,3)){
        var objUrl = getObjectURL(obj.files[0]);
        getImageWidth(objUrl, function(w, h) {
            var size = "?" + w + "/" + h;
            if (w > 750) {
                alert("图片尺寸太大，请处理成不大于750px");
                return false;
            }
            else{
                $.ajax({
                    url: appUrl + '/upload/' + action,
                    type: 'POST',
                    data: data,
                    cache: false,
                    contentType: false,
                    processData: false,
                    success: function (res) {
                        //获取图片尺寸
                        res = res + size;
                        //多图
                        if (flag) {
                            $(obj).before("<div class='detail-box'>" +
                                "<input type='hidden' name=" + at + " value=" + res + "  />" +
                                "<img class='test' src=" + res + " />" +
                                "<i class='fa fa-close'></i></div>");
                            //删除
                            $(".detail-box i").click(function () {
                                var detBox = $(this).parent();
                                $.ajax({
                                    url: appUrl + '/upload/remove',
                                    type: "POST",
                                    data: JSON.stringify({'name': res, 'id': 0}),
                                    dataType: "json",
                                    contentType: "application/json; charset=utf-8",
                                    success: function (res) {
                                        console.log(res);
                                        detBox.remove();
                                    }
                                });
                            });
                        }
                        //单图
                        else {
                            var _this = $(obj).parent();
                            _this.hide();
                            //预先取消绑定 -- 兼容webkit
                            _this.siblings(".obj-img").off("click");
                            _this.siblings(".obj-img").attr("src", res).show().on("click", function () {
                                $(obj).click();
                            });
                            _this.siblings(".obj-input").val(res);
                            _this.siblings("input.old-val").val(res).change();//编辑页面直接修改input的值
                        }
                    },
                    error: function () {
                        console.log("上传失败")
                    }
                });
            }
        });
    }
    //获取图片原始尺寸方法
    function getImageWidth(url,callback){
        var img = new Image();
        img.src = url;
        // 如果图片被缓存，则直接返回缓存数据
        if(img.complete){
            callback(img.width, img.height);
        }
        // 完全加载完毕的事件
        else{
            img.onload = function(){
                callback(img.width, img.height);
            }
        }
    }
    //判断图片大小
    function getPhotoSize(obj,imgSize){
        var photoExt = obj.value.substring(obj.value.lastIndexOf(".")+1).toLowerCase();//获得文件后缀名
        if(photoExt!='jpg'&&photoExt!='jpeg'&&photoExt!='bmp'&&photoExt!='png'){
            alert("图片格式必须是.jpg/.jpeg/.bmp/.png!");
            return false;
        }
        var imgSize = imgSize || 3;
        var fileSize = 0;
        var isIE = /msie/i.test(navigator.userAgent) && !window.opera;
        if (isIE && !obj.files) {
            var filePath = obj.value;
            var fileSystem = new ActiveXObject("Scripting.FileSystemObject");
            var file = fileSystem.GetFile (filePath);
            fileSize = file.Size;
        }else {
            fileSize = obj.files[0].size;
        }
        fileSize=Math.round(fileSize/1024*100)/100; //单位为KB
        if(fileSize>imgSize*1024){
            alert("图片最大为"+imgSize+"M，请重新上传!");
            return false;
        }
        return fileSize;
    }
    //获取图片临时url -- 1.判断图片尺寸 2.可实现预览
    function getObjectURL(file) {
        var url = null ;
        if (window.createObjectURL!=undefined) { // basic
            url = window.createObjectURL(file) ;
        } else if (window.URL!=undefined) { // mozilla(firefox)
            url = window.URL.createObjectURL(file) ;
        } else if (window.webkitURL!=undefined) { // webkit or chrome
            url = window.webkitURL.createObjectURL(file) ;
        }
        return url ;
    }
};
var vueUploadFile = function(obj,type,size) {
    var filetypes = type;
    var filepath = obj.value;

    var targetSize = size || 10;
    var fileSize = 0;
    var isIE = /msie/i.test(navigator.userAgent) && !window.opera;
    if (isIE && !obj.files) {
        var filePath = obj.value;
        var fileSystem = new ActiveXObject("Scripting.FileSystemObject");
        var file = fileSystem.GetFile (filePath);
        fileSize = file.Size;
    }else {
        fileSize = obj.files[0].size;
    }
    fileSize=Math.round(fileSize/1024*100)/100; //单位为KB
    if(fileSize>targetSize*1024){
        alert("文件最大为"+targetSize+"M，请重新上传!");
        return false;
    }
    if (filepath) {
        var isnext = false;
        var fileend = filepath.substring(filepath.lastIndexOf("."));
        if (filetypes && filetypes.length > 0 && (filetypes == fileend)) {
            //创建FormData对象
            var data = new FormData();
            var action = $(obj).attr("data-action");
            //为FormData对象添加数据
            data.append('image', $(obj)[0].files[0]);
            $.ajax({
                url: appUrl + '/upload/' + action,
                type: 'POST',
                data: data,
                cache: false,
                contentType: false,
                processData: false,
                success: function (res) {
                    console.log(res);
                    //            var fileName = $(obj).val().split("\\")
                    //            fileName = fileName[fileName.length - 1];
                    $(obj).siblings("#fileValue").val(res);
                    $(obj).siblings("#fileName") && $(obj).siblings("#fileName").attr("src", res).show();
                    $(obj).siblings("#fileText") && $(obj).siblings("#fileText").val(res).show();
                },
                error: function () {
                    console.log("上传失败")
                }
            })
        }
        else{
            alert("不接受此文件类型！");
            obj.value = "";
            return false;
        }
    } else {
        return false;
    }
}